package com.wx.springboot.step6.service.impl;

import com.wx.springboot.step6.component.JwtTokenUtil;
import com.wx.springboot.step6.dao.ExtPermissionMapper;
import com.wx.springboot.step6.dto.AdminLoginParam;
import com.wx.springboot.step6.enums.AdminEnums;
import com.wx.springboot.step6.exception.ApiAssert;
import com.wx.springboot.step6.exception.ApiException;
import com.wx.springboot.step6.mbg.mapper.AdminMapper;
import com.wx.springboot.step6.mbg.model.Admin;
import com.wx.springboot.step6.mbg.model.AdminExample;
import com.wx.springboot.step6.mbg.model.Permission;
import com.wx.springboot.step6.service.AdminService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class AdminServiceImpl implements AdminService {
    @Autowired
    private UserDetailsService userDetailsService;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Value("${jwt.tokenHead}")
    private String tokenHead;
    @Autowired
    private AdminMapper adminMapper;
    @Autowired
    private ExtPermissionMapper extPermissionMapper;

    @Override
    public Admin getAdminByUsername(String username) {
        AdminExample example = new AdminExample();
        example.createCriteria().andUsernameEqualTo(username);
        List<Admin> adminList = adminMapper.selectByExample(example);
        if (adminList != null && adminList.size() > 0) {
            return adminList.get(0);
        }
        return null;
    }

    @Override
    public Admin register(AdminLoginParam adminLoginParam) {
        //查询是否有相同用户名的用户
        AdminExample example = new AdminExample();
        example.createCriteria().andUsernameEqualTo(adminLoginParam.getUsername());
        List<Admin> adminList = adminMapper.selectByExample(example);
        if (adminList.size() > 0) {
            ApiAssert.failed("用户已存在.");
        }
        Admin admin = new Admin();
        BeanUtils.copyProperties(adminLoginParam, admin);
        admin.setCreateTime(new Date());
        admin.setStatus(AdminEnums.StatusEnum.STATUS_YES.getCode());
        //将密码进行加密操作
        String encodePassword = passwordEncoder.encode(admin.getPassword());
        admin.setPassword(encodePassword);
        adminMapper.insert(admin);
        return admin;
    }

    @Override
    public String login(String username, String password) {
        String token = null;
        try {
            UserDetails userDetails = userDetailsService.loadUserByUsername(username);
            if (!passwordEncoder.matches(password, userDetails.getPassword())) {
                throw new ApiException("密码不正确");
            }
            UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
            SecurityContextHolder.getContext().setAuthentication(authentication);
            token = jwtTokenUtil.generateToken(userDetails);
        } catch (AuthenticationException e) {
            log.warn("登录异常:{}", e.getMessage());
        }
        return token;
    }


    @Override
    public List<Permission> getPermissionList(Long adminId) {
        return extPermissionMapper.getPermissionList(adminId);
    }
}
